import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { getToken,isTokenFromLocalStorageVaild,logOut } from '@/auth/auth.service'

const routes = [
  {
	path: '/login',
	name: 'login',
	component: () => import('@/auth/views/UserLogin.vue')
  },
  {
    path: '/',
    name: '/',
    component: () => import('@/views/LayoutView.vue'),
	redirect:'/home',
	children:[
	{
	path: '/home',
	name: 'home',
	component: HomeView
	},
	{
	path: '/about',
	name: 'about',
	// route level code-splitting
	// this generates a separate chunk (about.[hash].js) for this route
	// which is lazy-loaded when the route is visited.
	component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
	},
	{
		path: '/category',
		name: 'category',
		component: () => import( '../views/CategoryView.vue')
	},
	{
		path: '/addCategory',
		name: 'addCategory',
		component: () => import( '../components/AddCategory.vue')
	},
	{
		path: '/shop',
		name: 'shop',
		component: () => import( '../views/shopView.vue')
	}
	]
  },
  
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

//全局导航守卫(前置/后置)、独享守卫、组件内守卫
router.beforeEach((to,from,next)=>{
	//to:可以获取到目的地的路由
	//from:可以获取到从哪里来的路由
	//next():继续、放行 (用法1--next()表示继续、2--next("/login") 去哪里、3--next(false) 取消当前导航)
	
	//通过token判断有没有登录
	if(getToken()){
		//已登录(就不能去登录页了)
		if(to.path == "/login"){
			next("/")
		}else{
			//检查token有没有过期
			if(isTokenFromLocalStorageVaild()){
				//未过期
				next()
				
			}else{
				logOut()//清除过期token
				//已过期
				//next("/login")
			}
			//next()
		}
		
		console.log("已登录")
	}else{
		//未登录
		if(to.path=="/login"){
			next()
		}else{
			next("/login")
		}

		console.log("未登录")
	}

	
})

export default router
